package com.jushu.storbox;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;

import com.jushu.storbox.adapter.FileBrowserDocumentAdapter;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.DirectoryManager;
import com.jushu.storbox.util.LogUtil;

/**
 * <ol>
 * <li>&lt;uses-permission
 * android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;</li>
 * <li>&lt;uses-permission
 * android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;</li>
 * </ol>
 * 
 */
public class FileBrowserDocumentActivity extends Activity {
	private DirectoryManager directoryManager;

	/** ListView for Document */
	private ListView document_files;

	private FileBrowserDocumentAdapter adapter;

	private List<File> datas;

	private File rootDir;

	private String[] mFilters;

	private ProgressDialog waitDialog;

	private static final int HANDLER_CODE_DISSMISS_DIALOG = 1;

	private static final int HANDLER_CODE_SHOW_DIALOG = 2;

	private Handler handler = null;

	private final static String LOG_TAG = "FileBrowserDocumentActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtil.i(LOG_TAG, "onCreate()");
		isSDCardExist();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_docment);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG,
				FileBrowserDocumentActivity.this);
		init();
		findViews();
		setAdapter();
		setListeners();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		LogUtil.i(LOG_TAG, "onDestroy()");
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
	}

	private void setAdapter() {
		waitDialog = new ProgressDialog(this);
		waitDialog.setMessage(FileBrowserDocumentActivity.this.getString(R.string.loading));
		waitDialog.setCanceledOnTouchOutside(false);
		this.scanSDCard(mFilters);
	}

	private void setListeners() {

	}

	private void isSDCardExist() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String rootPath = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			rootDir = new File(rootPath);
		} else {
			rootDir = null;
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_LONG)
					.show();
		}
	}

	private void init() {
		directoryManager = DirectoryManager.getInstance();
		mFilters = getResources().getStringArray(R.array.SUFFIX_DOC);
		handler = new MyHandler();
	}

	private void findViews() {
		document_files = (ListView) findViewById(R.id.lv_document_files);
	}

	/**
	 * @param location
	 */
	private void scanSDCard(final String[] mFilters) {
		if (null == rootDir) {
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_LONG)
					.show();
			return;
		}

		new Thread() {
			@Override
			public void run() {
				if (datas == null) {
					datas = new ArrayList<File>();
				}
				handler.sendEmptyMessage(HANDLER_CODE_SHOW_DIALOG);
				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				directoryManager.getFileListing(rootDir, mFilters, datas);
				Message msg = Message.obtain();
				msg.what = HANDLER_CODE_DISSMISS_DIALOG;
				msg.obj = datas;
				handler.sendMessage(msg);
			};
		}.start();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			FileBrowserDocumentActivity.this.finish();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * @param view
	 */
	public void uploadOrCancel(View view) {
		switch (view.getId()) {
		case R.id.upload:
			Intent data = new Intent();
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("resultUIL", adapter.getSelectedFiles());
			data.putExtra("result", bundle);
			setResult(2, data);
			FileBrowserDocumentActivity.this.finish();
			// Toast.makeText(this, adapter.getSelectedFiles().toString(),
			// Toast.LENGTH_LONG).show();
			break;

		case R.id.cancel:
			FileBrowserDocumentActivity.this.finish();
			break;
		}
	}

	@SuppressLint("HandlerLeak")
	private class MyHandler extends Handler {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_CODE_DISSMISS_DIALOG:
				waitDialog.dismiss();
				datas = (List<File>) msg.obj;
				adapter = new FileBrowserDocumentAdapter(datas,
						FileBrowserDocumentActivity.this);
				document_files.setAdapter(adapter);
				break;
			case HANDLER_CODE_SHOW_DIALOG:
				waitDialog.show();
				break;
			}
		}
	}

}
